#coding:utf8
import datetime,time
import smtplib
from email.mime.text import MIMEText    #导入MIMEText类

import logging
logger = logging.getLogger(__name__)

class sendEmallClass(object):
    def __init__(self, host, user, passwd, port=25):
        self.host = host
        self.user = user
        self.passwd = passwd
        self.port = port

    def doSendEmall(self, toList, ccList, subject='test', content='test'):
        msg = MIMEText(content, "html", "utf-8")
        msg["Subject"] = subject            # 邮件主题
        msg["From"] = self.user                  # 邮件发件人，邮件头部可见
        msg["To"] = ','.join(toList)            # 邮件收件人，邮件头部可见
        msg["Cc"] = ','.join(ccList)
        self._execSendEmail(toList, msg)


    def _execSendEmail(self, toList, msg):
        try:
            server = smtplib.SMTP()     #创建一个SMTP（）对象
            server.set_debuglevel(0)    #开启debug模式
            server.connect(self.host,self.port)   #通过connect方法连接smtp主机
            server.starttls()           #启动安全传输模式
            server.login(self.user,self.passwd)      #邮箱帐号登录检验
            server.sendmail(self.user, toList, msg.as_string())    #邮件发送
            server.quit()               #断开smtp连接
            logger.info('邮件发送成功')
        except Exception, e:
            logger.info('邮件发送失败'+str(e))


if __name__ == '__main__':
    #使用126邮箱给exchange发送邮件
    host = "smtp.exmail.qq.com"        #定义smtp主机
    subject = u"从126发送过来的邮件"      #定义邮件主题
    toList = "2368691083@qq.com, 986526367@qq.com"    #定义邮件收件人
    print 'toList is:',type(toList), len(toList),toList
    ccList = "mason@yunlai.cn, magicjms@sina.com"    #定义邮件抄送人
    print 'ccList is:',ccList
    user = "yunwei@yunlai.cn"   #定义邮件发件人
    passwd = "aCY@0724Lai"
    content = "<p style='color: red'>grafana回调测试邮件………………%s</p>" % (datetime.datetime.now())

    sendEmallObj = sendEmallClass(host, user, passwd)
    sendEmallObj.doSendEmall(toList, ccList, subject=subject, content=content)